package com.aorise.service.system.impl;

import com.aorise.exception.SystemException;
import com.aorise.mapper.system.RoleAuthorityMapper;
import com.aorise.mapper.system.RoleMapper;
import com.aorise.mapper.system.UserRoleMapper;
import com.aorise.model.request.UpdateRoleReq;
import com.aorise.model.response.RoleInfoRes;
import com.aorise.model.system.*;
import com.aorise.service.system.RoleService;
import com.aorise.utils.ConstDefine;
import com.aorise.utils.Page;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther: zhouhao
 * @Date: 2019/4/26
 * @Description:
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    RoleAuthorityMapper roleAuthorityMapper;

    @Override
    public List<Role> selectByUserId(User user) {

        UserRoleExample urExample =new UserRoleExample();
        urExample.or().andUser_idEqualTo(user.getId());
        urExample.or().andStateEqualTo(ConstDefine.STATE_ABLE);
        List<UserRole> userRoles = userRoleMapper.selectByExample(urExample);
        List<Integer> roids = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(roids)){
            return null;
        }
        RoleExample roleExample =new RoleExample();
        roleExample.or().andIdIn(roids);
        List<Role> roles = roleMapper.selectByExample(roleExample);
        return roles;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addRole(String roleName, List<Integer> permissions) {
        if(CollectionUtils.isEmpty(permissions)){
            throw new SystemException("权限为空，无法保存");
        }
        RoleExample roleExample = new RoleExample();
        roleExample.or().andRole_nameEqualTo(roleName);
        roleExample.or().andStateEqualTo(ConstDefine.STATE_ABLE);
        if(CollectionUtils.isNotEmpty(roleMapper.selectByExample(roleExample))){
            throw new SystemException("角色已存在,无法保存");
        }
        Integer loginId = getLoginUser().getId();
        Role role = Role.builder().roleName(roleName).createUser(loginId).updateUser(loginId).build();
        if(!getBoolean(roleMapper.insert(role))){
            return false;
        }
        List<RoleAuthority> roleAuthorities = Lists.newArrayList();
        permissions.stream().forEach(p->{
            roleAuthorities.add(RoleAuthority.builder().roleId(role.getId()).authorityId(p)
                    .createUser(loginId).updateUser(loginId).build());
        });
        return getBoolean(roleAuthorityMapper.insertList(roleAuthorities));
    }

    @Override
    public Page selectPageRole(String roleName,Integer pageSize,Integer pageNum) {
        Page page = new Page();
        pageSize = pageSize==null?10:pageSize;
        pageNum = pageNum==null?1:pageNum;
        page.setCurrentPage(pageNum.longValue());
        page.setEveryPage(pageSize.longValue());
        RoleExample roleExample =new RoleExample();
        if(StringUtils.isNotBlank(roleName)){
            roleExample.or().andRole_nameLike("%"+roleName+"%");
        }
        roleExample.or().andStateEqualTo(ConstDefine.STATE_ABLE);
        long count = roleMapper.countByExample(roleExample);
        if(count >0){
            page.setTotalCount(count);
            page.setTotalPage(count, page.getEveryPage());
            if (page.getCurrentPage() > 0 && page.getEveryPage() > 0) {
                Map<String, Object> map = new HashMap<>(4);
                map.put("roleName", roleName);
                map.put("beginIndex", page.getBeginIndex());
                map.put("endinIndex", page.getEndinIndex());
                /**查询分页条数*/
                page.setList(roleMapper.selectPageRole(map));
            }
        }else {
            page.setTotalCount(0L);
        }
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delRole(Integer roleId) {
        RoleExample roleExample = new RoleExample();
        roleExample.or().andIdEqualTo(roleId);
        roleExample.or().andStateEqualTo(ConstDefine.STATE_ABLE);
        if( !getBoolean(roleMapper.updateByExampleSelective(Role.builder().state(ConstDefine.STATE_DISABLE).build(), roleExample))){
            return false;
        }
        RoleAuthorityExample rAExample = new RoleAuthorityExample();
        rAExample.or().andRole_idEqualTo(roleId);
        rAExample.or().andStateEqualTo(ConstDefine.STATE_ABLE);
        return getBoolean(roleAuthorityMapper.updateByExampleSelective(RoleAuthority.builder().state(ConstDefine.STATE_DISABLE).build(),rAExample));
    }

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = { Exception.class })
    @Override
    public boolean updateRole(UpdateRoleReq updateRoleReq) {
        if(CollectionUtils.isEmpty(updateRoleReq.getPermissions())){
            throw new SystemException("权限为空，无法保存");
        }
        Integer roleId = updateRoleReq.getRoleId();
        Integer loginId = getLoginUser().getId();
        RoleAuthorityExample rAExample = new RoleAuthorityExample();
        rAExample.or().andRole_idEqualTo(roleId);
        rAExample.or().andStateEqualTo(ConstDefine.STATE_ABLE);
        /**删除当前角色权限*/
        roleAuthorityMapper.updateByExampleSelective(RoleAuthority.builder().state(ConstDefine.STATE_DISABLE).build(),rAExample);
        List<RoleAuthority> roleAuthorities = Lists.newArrayList();
        updateRoleReq.getPermissions().stream().forEach(p->{
            roleAuthorities.add(RoleAuthority.builder().roleId(roleId).authorityId(p)
                    .createUser(loginId).updateUser(loginId).build());
        });
        if(StringUtils.isNotBlank(updateRoleReq.getRoleName())){
            String roleName = updateRoleReq.getRoleName();
            RoleExample roleExample = new RoleExample();
            roleExample.or().andRole_nameEqualTo(roleName);
            roleExample.or().andStateEqualTo(ConstDefine.STATE_ABLE);
            List<Role> roles = roleMapper.selectByExample(roleExample);
            if(CollectionUtils.isNotEmpty(roles) &&  roleId != roles.get(0).getId()){
                throw new SystemException("角色已存在,无法保存");
            }
            Role role = Role.builder().id(roleId).roleName(roleName).build();
            roleMapper.updateByPrimaryKeySelective(role);
        }
        /**修改角色名称 */
        /**添加当前角色权限*/
        return getBoolean(roleAuthorityMapper.insertList(roleAuthorities));
    }

    @Override
    public List<RoleInfoRes> selectAllRole() {
        return roleMapper.selectAllRole();
    }

}
